%% Author: yang.zhd
%% Created: 2009-4-7
%% Description: TODO: Add description to client
-module(client).

%%
%% Include files
%%
-include("common.hrl").
-include("pp.hrl").

%%
%% Exported Functions
%%
-export([start/0]).

%%
%% API Functions
%%

%%
%% TODO: Add description of start/function_arity
%%
start() -> 
    {ok, Socket} = tcp_server:start_client("localhost", 3000, 1024),
    io:format("client start ok~n"),    
   
    receive
        {packet, M1} ->
            M1;
        {tcp, _, Bin} ->
            case catch pp:read(Bin) of
                {'EXIT', Error} ->
                    error_logger:error_report(
                      [{module, ?MODULE},
                       {line, ?LINE},
                       {message, "Could not parse command"},
                       {Bin, Bin},
                       {error, Error},
                       {now, now()}]);
                #goto{ host = Host, port = Port} ->
                    Host1=binary_to_list(Host),
                    {ok, Socket1} = tcp_server:start_client(Host1, Port, 1024),
                    ?tcpsend(Socket1, #login{ nick = <<"abcd">>, pass = <<"@#%^@#">> }),
                    io:format("send ok~n")                       
            end;
        M3 ->
            M3
    end.

%%
%% Local Functions
%%

wait() ->
    wait(5000).

wait(Skip)
  when is_list(Skip) ->
    wait(5000, Skip);

wait(Timeout)
  when is_integer(Timeout) ->
    wait(Timeout, ['CANCEL', chat, ping, pong, notify_cancel_game]).

wait(Timeout, Skip) ->
    case receive
             {packet, M1} ->
                 M1;
             {tcp, _, M2} ->
                 pp:read(M2);
             M3 ->
                 M3
         after Timeout ->
                 {error, timeout}
         end of
        {error, timeout} = X ->
            X;
        M ->
            DoSkip = lists:member(element(1, M), Skip),
            if
                DoSkip ->
                    wait(Timeout, Skip);
                true ->
                    M
            end
    end.
